import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_fortune_wheel/flutter_fortune_wheel.dart';
import 'package:get/get_state_manager/get_state_manager.dart';
import 'package:get/instance_manager.dart';
import 'package:yp/config/index.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/mall_app/turntable/logic.dart';
import 'package:yp/pages/mall_app/turntable/state.dart';
import 'package:yp/router.dart';
import 'package:yp/widgets/dialog.dart';
import 'package:yp/widgets/index.dart';
import 'package:get/get.dart';
import 'dart:math' as math;

/// 大转盘
class TurntablePage extends StatefulWidget {
  const TurntablePage({Key key}) : super(key: key);

  @override
  _TurntablePageState createState() => _TurntablePageState();
}

class _TurntablePageState extends State<TurntablePage> {
  final logic = Get.put(TurntableLogic());
  final TurntableState state = Get.find<TurntableLogic>().state;

  StreamController<int> _streamController = StreamController<int>.broadcast();

  @override
  void initState() {
    super.initState();
    logic.updateUICallback = () {
      setState(() {});
    };
  }

  @override
  void dispose() {
    super.dispose();
    _streamController.close();
  }

  @override
  Widget build(BuildContext context) {
    print(state.displayConfigure['homepage_background_picture_url']);
    return Scaffold(
        appBar: YPNavigationBar('大转盘'),
        backgroundColor: Color.fromARGB(255, 245, 35, 63),
        body: Stack(
          children: [
            state.displayConfigure['homepage_background_picture_url'] == null
                ? SizedBox()
                : Positioned.fill(
                    child: Image.network(
                    state.displayConfigure['homepage_background_picture_url'],
                    fit: BoxFit.cover,
                  )),
            Positioned(
                left: setWidth(32),
                top: setWidth(50),
                height: setWidth(70),
                child: InkWell(
                  onTap: () {
                    Get.toNamed(RouteConfig.turntableAward,
                        arguments: state, parameters: {'index': '1'});
                  },
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '我的奖品',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: setWidth(26),
                          decoration: TextDecoration.underline),
                    ),
                  ),
                )),
            Positioned(
                right: 0,
                top: setWidth(50),
                child: InkWell(
                    onTap: () {
                      Get.toNamed(RouteConfig.turntableAward,
                          arguments: state, parameters: {'index': '0'});
                    },
                    child: Container(
                      height: setWidth(70),
                      padding: EdgeInsets.only(
                          left: setWidth(20), right: setWidth(40)),
                      alignment: Alignment.centerLeft,
                      decoration: BoxDecoration(
                          color: Colors.black26,
                          borderRadius: BorderRadius.horizontal(
                              left: Radius.circular(setWidth(35)))),
                      child: Text(
                        '活动说明',
                        style: TextStyle(
                            color: Colors.white, fontSize: setWidth(26)),
                      ),
                    ))),
            state.bingoRewardFullConfigure.length == 0
                ? SizedBox(
                    width: 1,
                  )
                : Positioned(
                    left: (Get.width - setWidth(560)) / 2,
                    top: setWidth(350),
                    child: Container(
                      width: setWidth(560),
                      height: setWidth(560),
                      padding: EdgeInsets.all(setWidth(50)),
                      decoration: BoxDecoration(
                          image: state.displayConfigure[
                                      'turntable_frame_picture_url'] ==
                                  null
                              ? null
                              : DecorationImage(
                                  image: NetworkImage(state.displayConfigure[
                                      'turntable_frame_picture_url']))),
                      child: FortuneWheel(
                        /// 最终选中的值
                        selected: _streamController.stream,
                        animateFirst: false,
                        duration: Duration(seconds: 2),
                        // rotationCount: 100,
                        // 禁用手动旋转
                        physics: NoPanPhysics(),
                        // physics: TapPanPhysics(
                        //     activeSize: Size(setWidth(160), setWidth(160))),
                        indicators: [
                          FortuneIndicator(
                            child: Container(
                                width: setWidth(160),
                                height: setWidth(160),
                                child: state.displayConfigure[
                                            'draw_button_picture_url'] !=
                                        null
                                    ? Image.network(state.displayConfigure[
                                        'draw_button_picture_url'])
                                    : null),
                          ),
                        ],
                        onAnimationStart: () {
                          print('开始旋转');
                          state.isDrawing = true;
                        },

                        onFling: () {
                          print('手动旋转');
                        },
                        onAnimationEnd: () {
                          print('旋转结束');
                          state.isDrawing = false;
                          if (state.rewardInfo['reward_level'] != null) {
                            /// 中奖了
                            YpShowDialog.showCongratulations(
                                context, state.rewardInfo, () {
                              print('查看奖品');
                              Get.toNamed(RouteConfig.turntableAward,
                                  arguments: state, parameters: {'index': '1'});
                            });
                          } else {
                            /// 没中奖
                            YpShowDialog.showSorry(
                                context,
                                state.displayConfigure[
                                    'thanks_for_participation_picture_url']);
                          }
                        },
                        items: state.bingoRewardFullConfigure
                            .map((e) => FortuneItem(
                                style: FortuneItemStyle(
                                    borderColor: Config.mainColor),
                                child: Row(
                                  // mainAxisAlignment:
                                  //     MainAxisAlignment.spaceEvenly,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    SizedBox(
                                      width: setWidth(60),
                                    ),
                                    Container(
                                      height: setWidth(30),
                                      width: setWidth(85),
                                      alignment: Alignment.center,
                                      transform: Matrix4.rotationZ(math.pi / 2),
                                      transformAlignment: Alignment.center,
                                      child: Text(
                                        e['reward_level'] ?? '感谢参与',
                                        textDirection: TextDirection.ltr,
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            color: Config.mainColor,
                                            fontSize: setWidth(20)),
                                      ),
                                    ),
                                    Container(
                                        width: setWidth(60),
                                        height: setWidth(60),
                                        transform:
                                            Matrix4.rotationZ(math.pi / 2),
                                        transformAlignment: Alignment.center,
                                        child: Image.network(
                                          e['reward_picture_url'] ??
                                              state.displayConfigure[
                                                  'thanks_for_participation_picture_url'],
                                        )),
                                  ],
                                )))
                            .toList(),
                      ),
                    ),
                  ),
            Positioned(
                top: setWidth(350),
                child: Container(
                  height: setWidth(560),
                  width: Get.width,
                  child: Center(
                    child: InkWell(
                      onTap: () async {
                        if (state.isDrawing) {
                          return;
                        }
                        logic.draw((result) {
                          if (result) {
                            state.rewardInfo =
                                state.bingoRewardFullConfigure[state.giftNum];
                            _streamController.sink.add(state.giftNum);
                          }
                        });
                      },
                      child: SizedBox(
                        width: setWidth(160),
                        height: setWidth(160),
                      ),
                    ),
                  ),
                )),
            Positioned(
                top: setWidth(910),
                width: Get.width,
                child: Visibility(
                  visible: state.isEnable,
                  child: Center(
                      child: Column(
                    children: [
                      Visibility(
                          visible:
                              state.basicInfo['participant_show_flag'] == 1,
                          child: Text(
                              '已有' +
                                  '${state.awardListInfo['participant_count'] ?? 0}' +
                                  '人参与',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: setWidth(30),
                              ))),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text('总计剩余' + '${state.power['draw_count'] ?? 0}' + '次机会',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: setWidth(30),
                          )),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      InkWell(
                        onTap: () {
                          logic.getAwardChance();
                        },
                        child: Text('点击获取机会',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: setWidth(30),
                            )),
                      )
                    ],
                  )),
                )),
          ],
        ));
  }
}
